package com.kerrykidz.system.util.sync;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class RelationMessage extends BaseMessage {

	private String column;

	public RelationMessage(List<Map<String, Object>> datas, String tableName, String primaryKey, String primaryValue,
			String column) {
		this.datas = datas;
		this.tableName = tableName;
		this.isCommonTable = false;
		this.primaryKey = primaryKey;
		this.column = column;
		this.primaryValue = primaryValue;
	}

	private static final long serialVersionUID = 1L;

	protected List<Map<String, Object>> datas;

	@Override
	public SqlAndParam getDeleteSql() throws SyncDataException {
		StringBuffer sql = new StringBuffer("delete from ");
		sql.append(super.tableName).append(" where ").append(this.column).append("=?");
		return new SqlAndParam(sql.toString(), new Object[] { this.primaryValue });
	}

	/**
	 * 
	 * @Desc 获取批量插入sql
	 * @author QUINN
	 * @date 2014年9月18日下午6:34:20
	 * @return
	 */
	public SqlAndParam getBatchInsertSql() {
		if (datas == null || datas.size() == 0)
			return null;
		List<Object> params = new ArrayList<Object>();
		Map<String, Object> firstData = this.datas.get(0);
		StringBuffer sql = new StringBuffer("INSERT INTO ");
		sql.append(super.tableName).append(" (");
		sql.append(super.getFlds(firstData.keySet())).append(")VALUES");
		for (Map<String, Object> data : this.datas) {
			sql.append("(").append(super.getValues(data.values())).append("),");
			Collection<Object> os = data.values();
			for (Object o : os)
				params.add(o);
		}
		sql.delete(sql.length() - 1, sql.length());
		return new SqlAndParam(sql.toString(), params.toArray());
	}

	public void setDatas(List<Map<String, Object>> datas) {
		this.datas = datas;
	}

	public String getColumn() {
		return column;
	}

	public void setColumn(String column) {
		this.column = column;
	}

}
